const { User, Resource, Feedback, sequelize } = require('../models');

/**
 * 提交资源反馈
 * @route POST /api/feedback/submit
 */
const submitFeedback = async (req, res, next) => {
  try {
    const { resourceId, evaluation, suggestion, userId = 1 } = req.body;
    
    // 1. 检查资源是否存在
    const resource = await Resource.findByPk(resourceId);
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '资源不存在'
      });
    }
    
    // 2. 检查用户是否存在
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 3. 创建反馈记录
    const feedback = await Feedback.create({
      resourceId,
      userId,
      evaluation,
      suggestion,
      isTrainingSample: true // 默认标记为训练样本
    });
    
    // 4. 返回结果
    res.json({
      code: 200,
      success: true,
      message: '反馈已提交，感谢您的建议',
      data: {
        feedbackId: feedback.id
      }
    });
    
    // 5. 异步处理：将反馈同步至Coze平台（实际项目中实现）
    // 这里只是示意，实际项目中应该实现定期批量同步或实时同步
    // syncFeedbackToCoze(feedback).catch(err => console.error('同步反馈到Coze平台失败:', err));
    
  } catch (error) {
    next(error);
  }
};

/**
 * 获取反馈统计数据
 * @route GET /api/feedback/stats
 */
const getFeedbackStats = async (req, res, next) => {
  try {
    const { userId } = req.query;
    
    // 构建查询条件
    const whereCondition = {};
    if (userId) {
      whereCondition.userId = userId;
    }
    
    // 获取反馈总数
    const totalCount = await Feedback.count({
      where: whereCondition
    });
    
    // 获取满意/不满意数量
    const satisfiedCount = await Feedback.count({
      where: {
        ...whereCondition,
        evaluation: 'satisfied'
      }
    });
    
    const unsatisfiedCount = await Feedback.count({
      where: {
        ...whereCondition,
        evaluation: 'unsatisfied'
      }
    });
    
    // 按资源类型统计反馈
    const feedbackByResourceType = await Feedback.findAll({
      attributes: [
        [sequelize.col('Resource.type'), 'resourceType'],
        [sequelize.fn('COUNT', sequelize.col('Feedback.id')), 'count']
      ],
      include: [{
        model: Resource,
        attributes: []
      }],
      where: whereCondition,
      group: [sequelize.col('Resource.type')],
      raw: true
    });
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        totalCount,
        satisfiedCount,
        unsatisfiedCount,
        satisfactionRate: totalCount > 0 ? (satisfiedCount / totalCount) : 0,
        byResourceType: feedbackByResourceType
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  submitFeedback,
  getFeedbackStats
};